import axios from "axios";
import qs from "qs";
import app from "../main.js";
import { Loading } from 'element-ui';
import { Message } from 'element-ui';


/****** 创建axios实例 ******/
const service = axios.create({
    baseURL: 'http://localhost:8765',  // api的base_url
    timeout: 4000  // 请求超时时间
});

let loading;
/****** request拦截器==>对请求参数做处理 ******/
service.interceptors.request.use(config => {
	loading = Loading.service({
          lock: true,
          text: '正在加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
    })
	//两秒后必须给用户一个回应
	setTimeout(()=>{
		loading.close();
	}, 2000)
    config.headers['Content-Type'] = 'application/json;charset=UTF-8';
    return config;
}, error => {
	console.log("请求失败")
	//请求错误处理
	Message.error({
		showClose: true,
		message: error
	})
    Promise.reject(error)
});


/****** respone拦截器==>对响应做处理 ******/
service.interceptors.response.use(
    response => {  //成功请求到数据
        loading.close();
        if (response.data.code === 200) {
			if(response.data.data ===true){
				Message.success({
					showClose:true,
					message: response.data.msg
				})
			}
            return response.data;
        }else if(response.status ===200){
			return response;
		} else {
            Message.error({
            	showClose: true,
            	message: response.data.msg
            })
			return response.data
        }
    },
    error => {  //响应错误处理
        let text = JSON.parse(JSON.stringify(error)).status === 404
            ? '未发现页面'
            : error.response.data.msg === null ? '网络异常，请重试' : error.response.data.msg;
		Message.error({
			showClose: true,
			message: text
		})
		return Promise.reject(error);
    }
	
);
export default service;
